import React, { useState, useEffect, useRef, memo, Children } from 'react';
import { motion } from 'framer-motion';
import { useReactive } from 'ahooks';
import './index.less';

/**
 * @param {Function} onAnimateFinish 拖拽结束回调
 * @param {String} direction 方向 top bottom left right 
 */
const DrawerBox = ({ children, onAnimateFinish, height = 300, extra = 100, direction = 'bottom' }) => {
    
    const drawerRef = useRef(null);
    const dragThreshold = 30; // 定义拖拽打开抽屉的距离阈值，这里设置为50像素，可按需调整
    const maxDragDistance = 100; // 设置拖动的最大距离
    const states = useReactive({
        isOpen: false,
        startX: 0,
        dragX: 0
    })

    const { dragX, isOpen } = states;


    const handleDragStart = (event) => {
        states.dragX = 0;
        states.startX =event.pageY;
    };

    const handleDrag = (event) => {
        const xDiff = event.pageY - states.startX;
        const newDragX = Math.min(maxDragDistance, Math.max(-maxDragDistance, xDiff));
        states.dragX = newDragX;
    };

    const handleDragEnd = (event) => {
        const xDiff = event.pageY - states.startX;
        if (Math.abs(xDiff) >= dragThreshold) {
            states.isOpen = !isOpen;
        }
        states.dragX = 0;

        onAnimateFinish?.({
            open: states.isOpen,
            height: states.isOpen ? 300  : 100
        })
    };


    return (
        <div style={{ position: 'fixed', top: window.innerHeight - extra, left: 0, width: '100%' }}>
            <motion.div
                ref={drawerRef}
                style={{ height: '100%' }}
                initial={{ y: isOpen? -height + extra : 0 }}
                animate={{ y: isOpen? (-height + extra + dragX) : 0 }}
                transition={{ duration: 0.1, ease: "easeInOut" }}
                drag="y"
                dragElastic={0.2}
                dragMomentum={0} // 禁用惯性运动
                dragConstraints={{
                    left: 0,
                    right: 0,
                    top: -height,
                    bottom: height
                }}
                onDragStart={handleDragStart}
                onDrag={handleDrag}
                onDragEnd={handleDragEnd}
                // onAnimationComplete={() => {
                //     console.log("onAnimationEnd")
                //     onAnimateFinish?.({
                //         open: isOpen,
                //         height: states.isOpen ? 300  : 100
                //     })
                // }}
            >
                <div className="drawer-container">
                    <div className="drag-handle"></div>
                    <div className="drawer-content">
                        {children}
                    </div>
                </div>
            </motion.div>
        </div>
    );
};

export default DrawerBox;